package com.cognizant.app;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.cognizant.app.adapter.HomePageFragmentPagerAdapter;
import com.cognizant.app.adapter.LanguageSelectAdapter;
import com.cognizant.app.interf.OnItemClickListener;
import com.cognizant.app.ui.activity.BaseActivity;
import com.cognizant.app.ui.activity.SettingActivity;
import com.cognizant.app.ui.fragment.InputFragment;
import com.cognizant.app.ui.fragment.ScanFragment;
import com.cognizant.app.wiget.CustomDecoration;
import com.rxjava.model.HttpResponse;
import com.rxjava.model.MeetingInfoBean;
import com.rxjava.model.QRCodeInfoBean;
import com.rxjava.model.TokenInfo;
import com.rxjava.network.Network;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import us.zoom.sdk.MeetingService;
import us.zoom.sdk.MeetingServiceListener;
import us.zoom.sdk.ZoomError;
import us.zoom.sdk.ZoomSDK;
import us.zoom.sdk.ZoomSDKInitializeListener;

public class LaunchActivity extends BaseActivity implements Constants, ZoomSDKInitializeListener, MeetingServiceListener {
    private static String TAG = LaunchActivity.class.getName();
    private String qrCode;
    private ArrayList<Fragment> mList;
    private ImageView[] mImageViews;
    private ArrayList<String> languageList;
    private PopupWindow mPopupWindow;
    private int page;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.dots)
    LinearLayout layoutDots;
    @BindView(R.id.languagell)
    LinearLayout languagell;
    @BindView(R.id.main_setting)
    ImageView setting;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate");
        if (savedInstanceState == null) {
            ZoomSDK sdk = ZoomSDK.getInstance();
            sdk.initialize(this, APP_KEY, APP_SECRET, WEB_DOMAIN, this);
        } else {
            registerMeetingServiceListener();
        }

        JSONObject requestData = new JSONObject();
        /*try {
            requestData.put("username", "admin");
            requestData.put("password", "admin");
        } catch (JSONException e) {
            e.printStackTrace();
        }*/
        try {
            requestData.put("zoomMeetingId", 436164568);
            requestData.put("timezone", "GMT+08:00");
            requestData.put("lat", 112.234);
            requestData.put("lng", 113.213);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString());
        //login(requestBody);
        //Log.i(TAG,"after login");
        //searchQRCode("46WTDyUjTqylyEJhqoFk2Q==", "436164568", "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInVzZXJJZCI6IjEiLCJuYW1lIjoiYWRtaW4iLCJleHAiOjE1MzMyMzEzMzJ9.WkbkxiBoSnT2IbnwLgxRL9sx6wRYAQI54Alpx_RpZm687o_L7C0yl-hIKo546KeUysbavtN5-BXZyGQ_zu-QHbc0_Ho-rHVju6pHeS1U9DEvmnipdfHOGDrM8aME9Uyu987xoUzuQhxsxH5RJD3n3EIV_kal8lQu31XguYK1Dlc");
        //joinMeeting(requestBody,"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInVzZXJJZCI6IjEiLCJuYW1lIjoiYWRtaW4iLCJleHAiOjE1MzMyMzEzMzJ9.WkbkxiBoSnT2IbnwLgxRL9sx6wRYAQI54Alpx_RpZm687o_L7C0yl-hIKo546KeUysbavtN5-BXZyGQ_zu-QHbc0_Ho-rHVju6pHeS1U9DEvmnipdfHOGDrM8aME9Uyu987xoUzuQhxsxH5RJD3n3EIV_kal8lQu31XguYK1Dlc");
    }

    private void registerMeetingServiceListener() {
        ZoomSDK zoomSDK = ZoomSDK.getInstance();
        MeetingService meetingService = zoomSDK.getMeetingService();
        if (meetingService != null) {
            meetingService.addListener(this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(TAG, "onNewIntent()");
        page = intent.getIntExtra("targetPage", 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewPager.setCurrentItem(page, false);
    }

    @Override
    protected void initView() {
        initViewPager();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void setListener() {

    }

    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        mList = new ArrayList<Fragment>();
        mList.add(new ScanFragment());
        mList.add(new InputFragment());
        // 底部点点实现
        mImageViews = new ImageView[mList.size()];
        for (int i = 0; i < mList.size(); i++) {
            mImageViews[i] = new ImageView(LaunchActivity.this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            // 设置边界
            params.setMargins(5, 0, 5, 0);
            mImageViews[i].setLayoutParams(params);
            if (0 == i) {
                mImageViews[i].setBackgroundResource(R.mipmap.dot_select);
            } else {
                mImageViews[i].setBackgroundResource(R.mipmap.dot_normal);
            }
            layoutDots.addView(mImageViews[i]);
        }

        viewPager.setAdapter(new HomePageFragmentPagerAdapter(getSupportFragmentManager(), mList));
        // 绑定回调
        viewPager.addOnPageChangeListener(new onPageChangeListener());
//        viewPager.setCurrentItem(0);
    }

    @Override
    public void onMeetingEvent(int i, int i1, int i2) {

    }

    @Override
    public void onZoomSDKInitializeResult(int errorCode, int internalErrorCode) {
        if (errorCode != ZoomError.ZOOM_ERROR_SUCCESS) {
            Toast.makeText(this, "Failed to initialize Zoom SDK. Error: " + errorCode + ", internalErrorCode=" + internalErrorCode, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "Initialize Zoom SDK successfully.", Toast.LENGTH_LONG).show();
            registerMeetingServiceListener();
        }
    }

    @Override
    protected void onDestroy() {
        ZoomSDK zoomSDK = ZoomSDK.getInstance();

        if (zoomSDK.isInitialized()) {
            MeetingService meetingService = zoomSDK.getMeetingService();
            meetingService.removeListener(this);
        }

        super.onDestroy();
    }

    /**
     * 监听ViewPager滑动效果
     */
    private class onPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            // 更新小圆点图标
            for (int i = 0; i < mList.size(); i++) {
                if (position == i) {
                    page = i;
                    mImageViews[i].setBackgroundResource(R.mipmap.dot_select);
                } else {
                    mImageViews[i].setBackgroundResource(R.mipmap.dot_normal);
                }
            }

//        // 滑动到最后pager时显示“立刻体验”按钮并监听
//        if (position == mList.size() - 1) {
//            onButtonClick();
//        } else {
//            btnImExp.setVisibility(View.INVISIBLE);
//        }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    @OnClick(R.id.main_setting)
    public void set() {
        startActivity(new Intent(this, SettingActivity.class));
    }

    @OnClick(R.id.languagell)
    public void switchLangusge() {
        showPopupWindow();
    }

    private void showPopupWindow() {
        languageList = new ArrayList<String>();
        languageList.add("简体中文");
        languageList.add("English");
        View view = LayoutInflater.from(this).inflate(R.layout.language_popupwindow, null);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_select);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        LanguageSelectAdapter languageSelectAdapter = new LanguageSelectAdapter(this, languageList);
        recyclerView.addItemDecoration(new CustomDecoration(this, CustomDecoration.VERTICAL));
        recyclerView.setAdapter(languageSelectAdapter);
        languageSelectAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                Log.i("maolikui", "position :" + postion + ",item:" + languageList.get(postion));
            }
        });
        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.showAsDropDown(languagell, 20, 0);
    }

    private void login(RequestBody requestBody) {
        Network.getLoginApi()
                .login(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<TokenInfo>() {
                    @Override
                    public void accept(TokenInfo tokenInfo) throws Exception {
                        Log.i(TAG, "accept success!");
                        if (tokenInfo != null) {
                            Log.i(TAG, "token str:" + tokenInfo.getToken());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.i(TAG, "Throwable error!Exception:" + throwable.getMessage());
                    }
                });
    }

    private void searchQRCode(String uuid, String meetingid, String token) {
        Network.getQRCodeInfoApi()
                .searchQRCode(uuid, meetingid, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<HttpResponse<QRCodeInfoBean>>() {
                    @Override
                    public void accept(HttpResponse<QRCodeInfoBean> qrCodeInfo) throws Exception {
                        Log.i(TAG, "accept success!");
                        if (qrCodeInfo != null) {
                            Log.i(TAG, "qrCodeInfo str:" + qrCodeInfo.getStatus());
                            Log.i(TAG, "qrCodeInfo str:" + qrCodeInfo.getData());
                            Log.i(TAG, "qrCodeInfo str:" + qrCodeInfo.getMessage());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.i(TAG, "Throwable error!Exception:" + throwable.getMessage());
                    }
                });
    }

    private void joinMeeting(RequestBody requestBody, String token) {
        Network.getMeetingInfoApi()
                .joinMeeting(requestBody, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<HttpResponse<MeetingInfoBean>>() {
                    @Override
                    public void accept(HttpResponse<MeetingInfoBean> meetingInfo) throws Exception {
                        Log.i(TAG, "meetingInfo status str:" + meetingInfo.getStatus());
                        Log.i(TAG, "meetingInfo data str:" + meetingInfo.getData().toString());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.i(TAG, "Throwable error!Exception:" + throwable.getMessage());
                    }
                });
    }
}
